package com.ripplezjw.blog.controller.admin;

import com.ripplezjw.blog.Service.UserService;
import com.ripplezjw.blog.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class UserInputController {
    @Autowired
    UserService userService;

    @GetMapping("userInput")
    public String userInput() {
        return "/admin/input/userInput";
    }

    @PostMapping("userInputTo")
    public String userInputTo(User user,
                              RedirectAttributes redirectAttributes) {
        String msg = userService.addUser(user);
        // 插入成功
        if (msg.isEmpty()) return "redirect:/admin/userMan";
        else {
            // 插入失败
            redirectAttributes.addFlashAttribute("user_input_error_msg", msg);
            return "redirect:/admin/userInput";
        }
    }

    @GetMapping("/userDel/{userId}")
    public String articleDel(Model model,
                             @PathVariable("userId") int userId) {
        userService.clickDelUserBtn(userId);
        return "redirect:/admin/userMan";
    }

    @GetMapping("/userMod/{userId}")
    public String userMod(@PathVariable("userId") int userId,
                          Model model) {
        User user = userService.clickModUserBtn(userId);
        model.addAttribute("user", user);
        return "/admin/input/userMod";
    }

    @PostMapping("/userMod/{userId}/to")
    public String userModTo(@PathVariable("userId") int userId,
                            User user,
                            RedirectAttributes redirectAttributes) {
        user.setUserId(userId);
        String msg = userService.modUser(user);
        // 更新成功
        if (msg.isEmpty()) return "redirect:/admin/userMan";
        else {
            // 更新失败
            redirectAttributes.addFlashAttribute("user_input_error_msg", msg);
            return "redirect:/admin/userMod/" + user.getUserId();
        }
    }
}
